package com.youlai.boot.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.core.security.model.UserAuthCredentials;
import com.youlai.boot.system.mapper.GlobalSysUserMapper;
import com.youlai.boot.system.model.entity.GlobalSysUser;
import com.youlai.boot.system.model.entity.Role;
import com.youlai.boot.system.model.entity.UserRole;
import com.youlai.boot.system.service.GlobalSysUserService;
import com.youlai.boot.system.service.RoleService;
import com.youlai.boot.system.service.UserRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 全局用户Service实现类
 *
 * @author youlaitech
 * @since 2025-11-08
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GlobalSysUserServiceImpl extends ServiceImpl<GlobalSysUserMapper, GlobalSysUser> implements GlobalSysUserService {

    private final UserRoleService userRoleService;
    private final RoleService roleService;

    @Override
    public GlobalSysUser getByOpenId(String openid) {
        if (StrUtil.isBlank(openid)) {
            return null;
        }

        return this.getOne(new LambdaQueryWrapper<GlobalSysUser>()
                .eq(GlobalSysUser::getOpenid, openid)
                .eq(GlobalSysUser::getIsDeleted, 0)
                .last("LIMIT 1"));
    }

    @Override
    public GlobalSysUser getByUnionId(String unionid) {
        if (StrUtil.isBlank(unionid)) {
            return null;
        }

        return this.getOne(new LambdaQueryWrapper<GlobalSysUser>()
                .eq(GlobalSysUser::getUnionid, unionid)
                .eq(GlobalSysUser::getIsDeleted, 0)
                .last("LIMIT 1"));
    }

        /**
     * 根据OpenID获取用户认证信息
     *
     * @param openId 微信OpenID
     * @return 用户认证信息
     */
    @Override
    public UserAuthCredentials getAuthCredentialsByOpenId(String openId) {
        if (StrUtil.isBlank(openId)) {
            return null;
        }
        UserAuthCredentials userAuthCredentials = this.baseMapper.getAuthCredentialsByOpenId(openId);
        if (userAuthCredentials != null) {
            Set<String> roles = userAuthCredentials.getRoles();
            // 获取最大范围的数据权限
            Integer dataScope = roleService.getMaximumDataScope(roles);
            userAuthCredentials.setDataScope(dataScope);
        }
        return userAuthCredentials;
    }

    @Override
    public GlobalSysUser registerWechatUser(String openid, String unionid) {
        log.info("注册新的全局用户，OpenID: {}, UnionID: {}", openid, unionid);

        GlobalSysUser globalUser = new GlobalSysUser();
        globalUser.setOpenid(openid);
        globalUser.setUnionid(unionid);
        globalUser.setNickname("微信用户");  // 默认昵称
        globalUser.setAvatar("https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif");  // 默认头像
        globalUser.setGender(0);  // 保密
        globalUser.setStatus(1);  // 正常状态
        globalUser.setUserType(1);  // 系统用户
        globalUser.setIsPrimary(0);  // 非主账号

        // 保存用户
        this.save(globalUser);

        // 插入sys_user_role表，用户的权限为游客
        Role guestRole = roleService.getOne(new LambdaQueryWrapper<Role>()
                .eq(Role::getCode, "GUEST")
                .eq(Role::getIsDeleted, 0)
                .last("LIMIT 1"));

        if (guestRole != null) {
            UserRole userRole = new UserRole();
            userRole.setUserId(globalUser.getId());
            userRole.setRoleId(guestRole.getId());
            userRoleService.save(userRole);
            log.info("为用户分配游客角色成功，用户ID: {}, 角色ID: {}", globalUser.getId(), guestRole.getId());
        } else {
            log.warn("未找到游客角色(GUEST)，无法为用户分配角色，用户ID: {}", globalUser.getId());
        }

        log.info("全局用户注册成功，用户ID: {}", globalUser.getId());
        return globalUser;
    }

    @Override
    public boolean updateTenantInfo(Long userId, Long tenantId, String tenantCode) {
        log.info("更新用户租户信息，用户ID: {}, 租户ID: {}, 租户编码: {}", userId, tenantId, tenantCode);

        return this.update(new LambdaUpdateWrapper<GlobalSysUser>()
                .eq(GlobalSysUser::getId, userId)
                .set(GlobalSysUser::getTenantId, tenantId)
                .set(GlobalSysUser::getTenantCode, tenantCode));
    }

    @Override
    public boolean updateUnionId(Long userId, String unionid) {
        if (StrUtil.isBlank(unionid)) {
            return false;
        }

        log.info("更新用户UnionID，用户ID: {}, UnionID: {}", userId, unionid);

        return this.update(new LambdaUpdateWrapper<GlobalSysUser>()
                .eq(GlobalSysUser::getId, userId)
                .set(GlobalSysUser::getUnionid, unionid));
    }
}

